function mle = SMLE_v2(params,data,random_draws, num_drugs, num_periods, id, outside, S)
%SMLE Computes likelihood function given data and parameter guess

    delta = params(1:3);
    
    alpha = params(4);
    % flatten and make it easier to evaluate in cases with no incumbent
    gamma = [params(5:7);params(8:10);params(11:13);0;0;0];
    sigma = params(14);
    
    random_draws = random_draws * sigma;
    
    % for readability
    drugid = data(:,3); % current drug id
    incumbent_id = data(:,6);
    incumbent_id(isnan(incumbent_id)) = 4;
    
    % STEP 1: transform data into ID, quarter u_ij based on parameters
    % Basic_part: drug quality - alpha * copay
    % NEW: data(6) marks the incumbent; apply gamma, then see if it is
    % actually the incumbent
    u = delta(data(:,3)) - ...
        alpha * data(:,5) + gamma(incumbent_id + 3 * (drugid-1)); % gamma matrix evaluated against two column vectors
    
    % repmat sideways and add random draw rows
    u = repmat(u,1,S) + random_draws(data(:,3) + num_drugs * (data(:,1) - 1), :);
    
    % STEP 2: aggregate and compute SMLE
    eu = exp(u);
    probs = zeros(size(outside,1),S);
    
    for i=1:S
        groupsum = 1 + accumarray(id, eu(:,i));
        eu_chosen = eu(:,i) .* data(:,4);
        chosen_sum = accumarray(id,eu_chosen);
        p = ((1 - outside) .* chosen_sum + outside * 1) ./ groupsum;
        
        probs(:,i) = p;
    end

    
    mean_probs= mean(probs,2);
    mle = sum(log(mean_probs));
end

